<?php

  //
  // Memorii Web
  // script/db_folder.php
  //
  // Access to the database
  //
  
  // Name of the table
  define('MII_TABLE_FOLDERS', 'mii_folders');
  
	function db_get_folder($db_connection, $folder_id) {
		db_clear_input($folder_id);
		
		$query = 'SELECT * FROM `'.MII_TABLE_FOLDERS.'` WHERE (`folder_id` = \''.$folder_id.'\')';
		$result = db_query_array($db_connection, $query);
		if($result)
			return $result;
			
		return array();
	}
	
	function db_get_subfolders($db_connection, $folder_id) {
		db_clear_input($folder_id);
		
		$query = 'SELECT * FROM `'.MII_TABLE_FOLDERS.'` WHERE (`parent_folder_id` = \''.$folder_id.'\') ORDER BY `order` ASC ';
		$result = db_query_arrays($db_connection, $query);
		if($result)
			return $result;
			
		return array();
	}
  	
	function db_add_subfolder($db_connection, $parent_folder_id) {
		db_clear_input($root_folder_id);
		
		$new_folder_id = db_generate_id();
		
		$query = 'INSERT INTO `'.MII_TABLE_FOLDERS.'` (`folder_id`, `parent_folder_id`, `name`, `icon`, `order`) VALUES (\''.$new_folder_id.'\', \''.$parent_folder_id.'\', \'New folder\', \'\', \'-1\') ';
		db_query($db_connection, $query);
		
		$query = 'SELECT MAX(`order`) FROM `'.MII_TABLE_FOLDERS.'` WHERE (`parent_folder_id` = \''.$parent_folder_id.'\')';
		$result = db_query_array($db_connection, $query);
		$query = 'UPDATE `'.MII_TABLE_FOLDERS.'` SET `order`=\''.(intval($result[0])+1).'\' WHERE (`folder_id` = \''.$new_folder_id.'\')';
		db_query($db_connection, $query);
	}
	
	function db_rename_folder($db_connection, $folder_id, $new_name) {
		db_clear_input($folder_id);
		db_clear_input($new_name);
		
		$query = 'UPDATE `'.MII_TABLE_FOLDERS.'` SET `name`=\''.$new_name.'\' WHERE `folder_id`=\''.$folder_id.'\'';
		db_query($db_connection, $query);
	}
		
	function db_delete_folder($db_connection, $folder_id) {
		db_clear_input($folder_id);
		
		$query = 'DELETE FROM `'.MII_TABLE_FOLDERS.'` WHERE `folder_id`=\''.$folder_id.'\' LIMIT 1';
		db_query($db_connection, $query);
		
		// TODO: recursive delete
	}
	
?>